//
//  UIView+KP.m
//  Keping
//
//  Created by 柯平 on 2017/7/11.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "UIView+KP.h"
#import <objc/runtime.h>

static const char *TapActionBlockKey;

@implementation UIView (KP)

-(void)appear
{
    [self setTransform:CGAffineTransformMakeScale(0.3, 0.3)];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.4f];
    [self setTransform:CGAffineTransformMakeScale(1.0f, 1.0f)];
    [UIView commitAnimations];
}

-(void)disappearWithSelector:(SEL)selector
{
    [self setTransform: CGAffineTransformMakeScale(1.0f, 1.0f)];
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationDuration: 0.4f];
    [UIView setAnimationDelegate: self] ;
    [UIView setAnimationDidStopSelector: selector];
    [self setTransform: CGAffineTransformMakeScale(0.001, 0.001)];
    [UIView commitAnimations];
}

-(void)setRoundedCorners:(UIRectCorner)corners radius:(CGFloat)radius
{
    CGRect rect = self.bounds;
    
    //Create the path
    UIBezierPath* maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    
    //Create the shape layer and set its path
    CAShapeLayer* maskLayer = [CAShapeLayer layer];
    maskLayer.frame = rect;
    maskLayer.path = maskPath.CGPath;
    
    // Set the newly created shape layer as the mask for the view's layer
    self.layer.mask = maskLayer;
}

-(UIView *)findFirstResponser
{
    if ([self isFirstResponder]) {
        return self;
    }
    
    for (UIView* subView in [self subviews]) {
        UIView* firstResponder = [subView findFirstResponser];
        if (nil != firstResponder) {
            return firstResponder;
        }
    }
    return nil;
}

-(void)setTapActionWithBlock:(void (^)(void))block{
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer* tapGesture = objc_getAssociatedObject(self, &TapActionBlockKey);
    if (!tapGesture) {
        tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBlockActionWithGesture:)];
        [self addGestureRecognizer:tapGesture];
        objc_setAssociatedObject(self, &TapActionBlockKey, tapGesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &TapActionBlockKey, block, OBJC_ASSOCIATION_COPY);
}

-(void)tapBlockActionWithGesture:(UITapGestureRecognizer*)gesture{
    if (gesture.state == UIGestureRecognizerStateRecognized) {
        void(^action)(void) = objc_getAssociatedObject(self, &TapActionBlockKey);
        if (action) {
            action();
        }
    }
}

@end
